package com.gimhon.login.service.impl;

import com.gimhon.login.entity.User;
import com.gimhon.login.repository.jpa.UserRepository;
import com.gimhon.login.service.api.UserService;
import com.mysql.cj.util.StringUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserRepository userRepository;

    @Override
    public User addUser(User user) {
        Date now = new Date();
        user.setUserId(StringUtils.getUniqueSavepointId().replace("_", ""));
        user.setCreateTime(now);
        user.setUpdateTime(now);
        user.setLastloginTime(now);
        user.setPassword(DigestUtils.md5Hex(user.getPassword()));
        User userInfo = userRepository.findByUsername(user.getUsername());
        if (userInfo != null) {
            return null;
        }
        return userRepository.save(user);
    }

    @Override
    public List<User> getUserList() {
        return userRepository.findAll();
    }

    @Override
    public User getUserByName(String name) {
        return null;
    }

    @Override
    public User updateUser(User user) {
        return null;
    }

    @Override
    public User login(User user) {
        String userName = user.getUsername();
        String pwd = user.getPassword();
        User userInfo = userRepository.findByUsernameAndPassword(userName,pwd);
        return userInfo;
    }
}
